package com.ms.education.course.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.education.course.constant.ClassTeacherRoleConstant;
import com.ms.education.course.entity.ClassTeacher;
import com.ms.education.course.entity.ClassUser;
import com.ms.education.course.entity.Classroom;
import com.ms.education.course.entity.Course;
import com.ms.education.course.entity.fo.Teacher;
import com.ms.education.course.entity.vo.ClassTeacherVo;
import com.ms.education.course.entity.vo.FrontClassInfoVo;
import com.ms.education.course.entity.vo.PageClassVo;
import com.ms.education.course.mapper.ClassroomMapper;
import com.ms.education.course.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.education.course.service.feign.UcenterFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级 服务实现类
 * </p>
 *
 * @author ms
 * @since 2023-02-24
 */
@Service
public class ClassroomServiceImp extends ServiceImpl<ClassroomMapper, Classroom> implements ClassroomService {

    @Autowired
    private ClassUserService classUserService;

    @Autowired
    private ClassTeacherService classTeacherService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private UcenterFeignService ucenterFeignService;

    @Override
    public Page<Classroom> pageClass(long current, long limit, PageClassVo pageClassVo) {
        Page<Classroom> page = new Page<>(current, limit);
        String name = pageClassVo.getName();
        Integer teacherId = pageClassVo.getTeacherId();
        Integer userId = pageClassVo.getUserId();
        String status = pageClassVo.getStatus();
        QueryWrapper<Classroom> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        wrapper.orderByAsc("priority").orderByDesc("gmt_create");
        //若用户id不为空，说明是前台用户在查询自己加入的班级
        if (!StringUtils.isEmpty(userId)) {
            QueryWrapper<ClassUser> w = new QueryWrapper<ClassUser>().eq("user_id", userId);
            List<Integer> classIds = classUserService.list(w).stream().map(ClassUser::getClassId).collect(Collectors.toList());
            if (!classIds.isEmpty()) {
                wrapper.in("id", classIds);
                return this.page(page, wrapper);
            } else {
                return page;
            }
        }
        //后天系统在管理班级
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(teacherId) && !pageClassVo.getIsAdmin()) {
            QueryWrapper<ClassTeacher> w = new QueryWrapper<ClassTeacher>().eq("teacher_id", teacherId);
            List<ClassTeacher> classTeachers = classTeacherService.list(w);
            if (!classTeachers.isEmpty()) {
                List<Integer> classIds = classTeachers.stream().map(ClassTeacher::getClassId).collect(Collectors.toList());
                wrapper.in("id", classIds);
                this.page(page, wrapper);
                //补充权限
                Map<Integer, Integer> map = classTeachers.stream().collect(Collectors.toMap(ClassTeacher::getClassId, ClassTeacher::getRole));
                for (Classroom classroom : page.getRecords()) {
                    classroom.setRole(map.get(classroom.getId()));
                }
                return page;
            } else {
                return page;
            }

        }
        if (!StringUtils.isEmpty(teacherId)) {
            QueryWrapper<ClassTeacher> w = new QueryWrapper<ClassTeacher>().eq("teacher_id", teacherId);
            List<ClassTeacher> classTeachers = classTeacherService.list(w);
            if (!classTeachers.isEmpty()) {
                List<Integer> classIds = classTeachers.stream().map(ClassTeacher::getClassId).collect(Collectors.toList());
                wrapper.in("id", classIds);
            }
        }
        if (pageClassVo.getExcludes() != null && !pageClassVo.getExcludes().isEmpty()) {
            wrapper.notIn("id", pageClassVo.getExcludes());
        }
        this.page(page, wrapper);
        if (pageClassVo.getIsAdmin()) {
            page.getRecords().forEach(c -> c.setRole(999));
        }
        return page;
    }

    @Override
    public List<Classroom> getClassOfUser(int userId) {
        return baseMapper.getClassOfUser(userId);
    }

    @Transactional
    @Override
    public void deleteClass(Integer id) {
        //删除班级用户关系表
        UpdateWrapper<ClassUser> wrapper1 = new UpdateWrapper<ClassUser>().eq("class_id", id);
        classUserService.remove(wrapper1);
        //删除班级讲师关系表
        UpdateWrapper<ClassTeacher> wrapper2 = new UpdateWrapper<ClassTeacher>().eq("class_id", id);
        classTeacherService.remove(wrapper2);
        //删除课程章节小节
        List<Integer> courseIds = courseService.list(new QueryWrapper<Course>().eq("class_id", id).select("id")).stream().map(Course::getId).collect(Collectors.toList());
        Integer[] ids = ArrayUtil.toArray(courseIds.iterator(), Integer.class);
        if (ids.length > 0) {
            courseService.deleteCourseByIds(ids);
        }

        //删除班级
        this.removeById(id);
    }

    @Override
    @Transactional
    public void saveClass(Classroom classroom) {
        this.save(classroom);
        ClassTeacher classTeacher = new ClassTeacher();
        classTeacher.setClassId(classroom.getId());
        classTeacher.setTeacherId(classroom.getTeacherId());
        classTeacher.setRole(ClassTeacherRoleConstant.ALL);
        classTeacherService.save(classTeacher);
    }

    @Override
    public List<ClassTeacherVo> getClassTeacher(Integer classId) {
        return baseMapper.getClassTeacher(classId);
    }

    @Override
    public FrontClassInfoVo getFrontClassInfo(Integer id) {
        FrontClassInfoVo res = new FrontClassInfoVo();
        Classroom classroom = getById(id);
        res.setInfo(classroom);
        if (classroom != null) {
            //查询班级课程
            List<Course> courses = courseService.list(new QueryWrapper<Course>().eq("class_id", id));
            res.setCourses(courses);
            //查询班级讲师
            List<Integer> teacherIds = classTeacherService.list(new QueryWrapper<ClassTeacher>().eq("class_id", id).select("teacher_id")).stream().map(ClassTeacher::getTeacherId).collect(Collectors.toList());
            if (!teacherIds.isEmpty()) {
                //远程调用
                List<Teacher> teachers = ucenterFeignService.getTeacherByIds(teacherIds);
                res.setTeachers(teachers);
            }
        }
        return res;
    }


}
